package com.example.funnyspringbootstarter.autoconfig;

import io.WriterTemplate;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.sql.SQLException;

@Configuration
@ConditionalOnClass(WriterTemplate.class)
//FunnyProperties是自定义的类，后面会定义
@EnableConfigurationProperties(FunnyProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class FunnyAutoConfiguration {
    private final FunnyProperties properties;

    public FunnyAutoConfiguration(FunnyProperties properties) {
        this.properties = properties;
    }

    @Bean(destroyMethod = "close")
    @ConditionalOnSingleCandidate(DataSource.class)
    @ConditionalOnMissingBean
    @AutoConfigureOrder(99)
    public WriterTemplate writerTemplate(DataSource dataSource) throws SQLException{
        return new WriterTemplate(dataSource);
    }


    @Bean(destroyMethod = "close")
    @ConditionalOnMissingBean
    @AutoConfigureOrder(199)
    public WriterTemplate writerTemplate2() throws FileNotFoundException{
        File f = new File(this.properties.getDest());
        Charset charset = Charset.forName(this.properties.getCharset());
        return new WriterTemplate(f,charset);
    }
}
